import { logger } from '../../../types/constants'
import { ElementUtils } from './element'

/**
 * Shadow DOM 检查配置
 */
export interface ShadowDOMCheckOptions {
  enabled?: boolean // 是否启用 Shadow DOM 检查
  mode?: 'open' | 'closed' | 'both' // 检查的 Shadow DOM 模式
  requireShadowRoot?: boolean // 是否要求必须存在 ShadowRoot
  checkChildrenShadowDOM?: boolean // 是否检查子元素的 Shadow DOM
  checkChildrenExist?: boolean // 是否检查子元素是否存在
  childrenSelector?: string // 子元素选择器，用于检查子元素的 Shadow DOM
  customCheck?: (element: Element) => boolean // 自定义检查函数
}

/**
 * 元素检查结果
 */
export interface ElementCheckResult {
  element: Element
  hasShadowRoot: boolean
  shadowRootMode?: 'open' | 'closed' | null
  shadowRoot?: ShadowRoot | null
  childrenIsExists: boolean
  childrenWithShadow: Element[]
}

/**
 * 阴影 DOM 样式工具类
 */
export class ShadowStyleUtils {
  static get name(): string {
    return 'ShadowStyleUtils'
  }

  /**
   * 检查元素的 Shadow DOM 状态
   */
  static checkElementShadowDOM(element: Element, options?: ShadowDOMCheckOptions): ElementCheckResult {
    const { checkChildrenShadowDOM = false, checkChildrenExist = false, customCheck } = options || {}

    const result: ElementCheckResult = {
      element,
      hasShadowRoot: false,
      shadowRootMode: null,
      shadowRoot: null,
      childrenIsExists: false,
      childrenWithShadow: [],
    }

    try {
      // 检查元素本身的 ShadowRoot
      if (element.shadowRoot) {
        result.hasShadowRoot = true
        result.shadowRoot = element.shadowRoot
        result.shadowRootMode = 'open' // 如果能访问到，说明是 open 模式
      }
      else {
        // 尝试检查 closed ShadowRoot（通过特征判断）
        const isCustomElement = /-/.test(element.tagName.toLowerCase())
        const hasShadowHost = element.getAttribute('shadowroot') !== null

        if (isCustomElement || hasShadowHost) {
          result.hasShadowRoot = true
          result.shadowRootMode = 'closed'
        }
      }

      const childrenSelector = options?.childrenSelector || '*'
      const children = Array.from($(result.shadowRoot ? result.shadowRoot : element).find(childrenSelector))

      // 检查子元素的 Shadow DOM
      if (checkChildrenShadowDOM)
        result.childrenWithShadow = children.filter(child => child.shadowRoot || this.isShadowHost(child))

      // 检查子元素是否存在
      if (checkChildrenExist)
        result.childrenIsExists = children.length > 0

      // 自定义检查
      if (customCheck)
        result.hasShadowRoot = customCheck(element) && result.hasShadowRoot
    }
    catch (error) {
      logger.debug(`[${this.name}] Shadow DOM 检查出错:`, error)
    }

    return result
  }

  /**
   * 判断元素是否为 Shadow Host
   */
  static isShadowHost(element: Element | JQuery<HTMLElement>): boolean {
    if (ElementUtils.isJQueryObject(element))
      element = (element as JQuery<HTMLElement>)[0]

    return (
      element.shadowRoot !== null
      || element.getAttribute('shadowroot') !== null
      || /-/.test(element.tagName.toLowerCase())
      || element.attachShadow !== undefined
    )
  }
}
